package com.jysz.certificate.service.pm;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import com.jysz.certificate.persistence.dao.pm.PerformanceAssignDao;
import com.jysz.certificate.persistence.dao.pm.PerformanceAssignShopDetailDao;
import com.jysz.certificate.persistence.enums.PerformanceAssignStatus;
import com.jysz.certificate.persistence.enums.PostType;
import com.jysz.certificate.persistence.enums.mytask.Prwarningtype;
import com.jysz.certificate.persistence.model.mytask.Prewarning;
import com.jysz.certificate.persistence.model.pm.PerformanceAssign;
import com.jysz.certificate.persistence.model.pm.PerformanceAssignShopDetail;
import com.jysz.certificate.persistence.model.system.User;
import com.jysz.certificate.service.system.OrganizationService;
import com.jysz.certificate.service.system.UserService;
import com.jysz.certificate.utils.DateUtil;
import com.jysz.webcore.ssh.orm.hibernate.ThreadLocalHolder;
import com.jysz.webcore.ssh.orm.hibernate.support.Page;
import com.jysz.webcore.ssh.service.EntityService;

/**
 * @author <a href="mailto:javaengine@outlook.com">Kaca Rich</a>
 *
 */
@Service
public class PerformanceAssignShopDetailService extends EntityService<PerformanceAssignShopDetail, Long, PerformanceAssignShopDetailDao>{

	@Resource
	private PerformanceAssignShopDetailDao performanceAssignShopDetailDao;
	@Resource
	private PerformanceAssignDao performanceAssignDao;
	@Resource
	private UserService userService;
	@Resource
	private OrganizationService organizationService;
	
	@Override
	public PerformanceAssignShopDetailDao getEntityDao() {
		return performanceAssignShopDetailDao;
	}

	
	public Page<PerformanceAssignShopDetail> findPageByPerformanceAssign(
			PerformanceAssignShopDetail search, PerformanceAssign performanceAssign,
			int currentPage, int pageSize) {
		Criteria criteria = this.getEntityDao().createCriteria();
		criteria.add(Restrictions.eq("performanceAssign", performanceAssign));
		Criteria shopCriteria = criteria.createCriteria("shop");
		
		if(search != null){
			if(search.getShop() != null ){
				if(StringUtils.isNotBlank(search.getShop().getShopName())){
					shopCriteria.add(Restrictions.like("shopName", search.getShop().getShopName(), MatchMode.END));
				}
				
				if(StringUtils.isNotBlank(search.getShop().getShopMark())){
					shopCriteria.add(Restrictions.like("shopMark", search.getShop().getShopMark(), MatchMode.END));
				}
				
				if(search.getShop().getArea() != null && StringUtils.isNotBlank(search.getShop().getArea().getName())){
					Criteria areaCriteria = shopCriteria.createCriteria("area");
					areaCriteria.add(Restrictions.like("name", search.getShop().getArea().getName(), MatchMode.END));
				}
				
			}

		}
		
		shopCriteria.addOrder(Order.asc("area"));
		
		String userName = ThreadLocalHolder.get().toString();
		User user = userService.getUserByName(userName);
		if(PostType.Manager.equals(user.getPost())){
			performanceAssignShopDetailDao.addShopCriteria(shopCriteria, true, user);
		}
		
		return this.findPage(criteria, currentPage, pageSize);
	}

	/**
	 * 统计这个区域下所有店的金额
	 * 
	 * @param entity
	 * @return
	 */
	public double findAreaTotalAmount(PerformanceAssignShopDetail entity) {
		Criteria criteria = this.getEntityDao().createCriteria();
		criteria.setProjection(Projections.sum("areaTotalAmount"));
		criteria.add(Restrictions.eq("performanceAssign", entity.getPerformanceAssign()));
		Criteria shopCriteria = criteria.createCriteria("shop");
		shopCriteria.add(Restrictions.eq("area", entity.getShop().getArea()));
		
		Object obj = criteria.uniqueResult();
		return obj != null ? Double.valueOf(obj.toString()) : 0;
	}

	public PerformanceAssignStatus getPmStatusByUser(PerformanceAssign object, User user) {
		Criteria criteria = this.getEntityDao().createCriteria();
		criteria.setProjection(Projections.count("id"));
		criteria.add(Restrictions.eq("performanceAssign", object));
		criteria.add(Restrictions.disjunction().add(Restrictions.isNull("status")).add(Restrictions.eq("status", PerformanceAssignStatus.NOT_CONFIRM)));
		
		//人员为空说明，不是区域经理。
		if(user == null){
			Criteria shopCriteria = criteria.createCriteria("shop");
			performanceAssignShopDetailDao.addShopCriteria(shopCriteria, true, user);
		}
		
		
		return Long.valueOf(criteria.uniqueResult().toString()) > 0 ? PerformanceAssignStatus.NOT_CONFIRM : PerformanceAssignStatus.CONFIRM;
	}

	@SuppressWarnings("unchecked")
	public List<PerformanceAssignShopDetail> findAreaShopDetailsByPerformanceAssign(
			PerformanceAssign entity) {
		
		Criteria criteria = this.getEntityDao().createCriteria();
		criteria.add(Restrictions.eq("performanceAssign", entity));
		Criteria shopCriteria = criteria.createCriteria("shop");
		performanceAssignShopDetailDao.addShopCriteria(shopCriteria, true, null);
		
		return criteria.list();
	}
	/**
	 * 添加预警信息     -------     绩效最后确认时间
	 * @param boo
	 * @param ki
	 * @return
	 */
	public List<Prewarning> prewarningList(User user){
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Set<Long> shopIdLongs = organizationService.fianPage(user);//获得该人员所有的店铺
		Date date= DateUtil.parseDate(DateUtil.formatDate(new Date(),"yyyy-MM"),"yyyy-MM");//获得当前时间
		List<Prewarning> prewarnings = new ArrayList<Prewarning>();
		PerformanceAssign performanceAssign = null;
		String date1 = null;//绩效确认最后时间
		String date2 = null ;//系统当前时间
		Long day = 0L;
		
		/**获得当月的绩效单*/
		Criteria criteriaPer =  performanceAssignDao.createCriteria();
		criteriaPer.add(Restrictions.ge("confirmPlanDate", DateUtil.getFirstdayLastdayMonthOne(date)));
		criteriaPer.add(Restrictions.le("confirmPlanDate", DateUtil.getFirstdayLastdayMonth(date)));
		criteriaPer.add(Restrictions.eq("status", PerformanceAssignStatus.NOT_CONFIRM));
		List<PerformanceAssign> performanceAssigns = criteriaPer.list();
		if(performanceAssigns.size()>0){
			performanceAssign = performanceAssigns.get(0);
		}
		if(performanceAssign != null){
			date1 = dateFormat.format(performanceAssign.getConfirmAssignDate());
			date2 = dateFormat.format(new Date());
			try {
				day = DateUtil.getDistanceDays(date1,date2);//计算时间差
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(day > 0 && day <=17){ //判断时间差   
			Criteria criteria = this.getEntityDao().createCriteria();
			criteria.add(Restrictions.eq("status", PerformanceAssignStatus.NOT_CONFIRM));//状态  待确认
			criteria.add(Restrictions.in("shop.id", shopIdLongs));
			List<PerformanceAssignShopDetail> performanceAssignShopDetails = criteria.list();
			if(performanceAssignShopDetails != null && performanceAssignShopDetails.size()>0){
					Prewarning prewarning = new Prewarning();
					String msg = "有绩效需要您确认！最后确认日期："+ performanceAssign.getConfirmAssignDate();
					prewarning.setBool(true);
					prewarning.setPrwarningtype(Prwarningtype.PERCENTAGE);
					prewarning.setMsg(msg);
					prewarning.setUrlAddress("cm/index.do");
					prewarnings.add(prewarning);
				
			}
		}
		
		return prewarnings;
		
	}

}
